package com.eduagent.xwqeduagent.api.OneSentenceReprint.api;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 获取训练文本服务
 */
@Service
public class TrainTextService {

    @Value("${xfyun.appid}")
    private String APPID;

    @Value("${xfyun.apikey}")
    private String APIKEY;

    @Autowired
    private AuthService authService;

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    private static final Gson GSON = new Gson();
    private static final String TRAINTEXT_URL = "http://opentrain.xfyousheng.com/voice_train/task/traintext";

    /**
     * 获取训练文本
     * @param token 鉴权token
     * @param textId 文本ID
     * @return 训练文本响应
     * @throws Exception 请求异常时抛出
     */
    public TrainTextResponse getTrainText(String token, Long textId) throws Exception {
        // 创建请求体
        Map<String, Object> requestJson = new HashMap<>();
        requestJson.put("textId", textId);
        String body = GSON.toJson(requestJson);
        
        // 设置请求类型和请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody httpBody = RequestBody.create(JSON, body);

        // 生成签名
        String time = String.valueOf(System.currentTimeMillis());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(APIKEY);
        stringBuilder.append(time);
        stringBuilder.append(AuthService.to32LowerCase(body.getBytes()));
        String signature = AuthService.to32LowerCase(stringBuilder.toString().getBytes());
        
        // 构建请求
        Request request = new Request.Builder()
                .url(TRAINTEXT_URL)
                .method("POST", httpBody)
                .addHeader("X-Sign", signature)
                .addHeader("X-Token", token)
                .addHeader("X-AppId", APPID)
                .addHeader("X-Time", time)
                .build();
        
        // 发送请求并获取响应
        Response response = HTTP_CLIENT.newCall(request).execute();
        TrainTextResponse trainTextResponse = GSON.fromJson(response.body().string(), TrainTextResponse.class);
        
        // 检查响应状态
        if (trainTextResponse.getCode() != 0) {
            throw new RuntimeException("获取训练文本失败: " + trainTextResponse.getDesc());
        }
        
        return trainTextResponse;
    }

    /**
     * 训练文本响应类
     */
    @Data
    public static class TrainTextResponse {
        private String flag;
        private int code;
        private String desc;
        private TextData data;
    }

    /**
     * 文本数据类
     */
    @Data
    public static class TextData {
        private long textId;
        private String textName;
        private List<TextSeg> textSegs;
    }

    /**
     * 文本段落类
     */
    @Data
    public static class TextSeg {
        @SerializedName("segId")
        private long segId;
        
        @SerializedName("segText")
        private String segText;
    }
} 